<template>
  <el-drawer v-model="drawerVisible" :destroy-on-close="true" :size="props.formSize" :title="`${drawerProps.title}`">
    <!-- 查询表单 -->
    <ProForm v-if="initFlag" ref="proForm" :columns="columns" :row="drawerProps.row" :readonly="drawerProps.readonly" />

    <el-form :model="drawerProps.row1" size="mini" label-width="90px" v-if="drawerProps.btn!.operatorType == 'AUDIT'">
      <el-divider content-position="left">审批结果</el-divider>
      <el-form-item label="审核结果">
        <el-radio v-model="drawerProps.row1._result" label="1">通过</el-radio>
        <el-radio v-model="drawerProps.row1._result" label="0">不通过</el-radio>
      </el-form-item>
      <el-form-item label="审核意见">
        <el-input type="textarea" v-model="drawerProps.row1._opinion" autocomplete="off"></el-input>
      </el-form-item>
    </el-form>

    <template #footer>
      <el-button type="primary" @click="handleSubmit">确定</el-button>
      <el-button @click="drawerVisible = false">取消</el-button>
    </template>
  </el-drawer>
</template>

<script setup lang="ts" name="ModDataDetail">
import { ref, reactive, onMounted } from "vue";
import { ProFormInstance, ColumnProps, SearchType } from "@/components/ProForm/interface";
import { ButtonProps } from "@/components/ProTable/interface";
import { Mod } from "@/api/interface";
import ProForm from "@/components/ProForm/index.vue";
import { ElMessage } from "element-plus";
import { OperatorType } from "@/enums/enum";
import { getModInfo, fireModData } from "@/api/modules/mod";
import { getColumnDataSource, getCustomDataSource } from "@/api/modules/system";

export interface ModDataDetailProps {
  modId: string;
  formSize: number;
}

// 默认值
const props = defineProps<ModDataDetailProps>();

// ProTable 实例
const proForm = ref<ProFormInstance>();

// 模块初标识
let initFlag = ref(false);
// 模块初配置信息
const config = reactive<Mod.SysModInfo>({
  modId: props.modId,
  isTreeList: "0",
  isFlow: "0",
  status: "0",
  formSize: props.formSize
});
//初始化值
const initValue = reactive({});

// 表格配置项
const columns = reactive<ColumnProps[]>([]);

// 初始化表单
const initForm = async () => {
  if (initFlag.value) return;

  let { data } = await getModInfo({ modId: props.modId });
  Object.assign(config, data);

  //设置表头
  let columns1 = data.columns!.sort((a, b) => a.controlOrderNum - b.controlOrderNum);

  columns1.forEach(item => {
    const column: any = {
      key: item.columnName,
      label: item.columnLabel,
      el: item.controlType as SearchType,
      span: item.controlWidth,
      visible: item.isHide !== "1",
      readonly: item.isReadonly === "1",
      multiple: item.isMultiple === "1"
    };

    //针对下拉框和下拉树
    if (item.controlType.startsWith("select") || item.controlType.startsWith("tree") || item.controlType.startsWith("cascader")) {
      //针对父级ID，单独处理
      if (item.columnName === config.pid) {
        column.enum = () => getCustomDataSource({ dataSourceCode: config.tableName! });
        column.fieldNames = { label: "name", value: "id" };
      } else {
        column.enum = () => getColumnDataSource({ columnId: item.columnId });
        column.fieldNames = { label: "name", value: "id" };
      }
    }

    //读取初始化值
    if (item.initValue !== null && item.initValue !== "") {
      initValue[item.columnName] = item.initValue;
    }

    columns.push(column);
  });

  initFlag.value = true;
};

onMounted(async () => {
  await initForm();
});

interface DrawerProps {
  title?: string;
  btn?: ButtonProps<any>;
  row?: any;
  row1?: any;
  getTableList?: () => void;
  readonly?: boolean;
}
const drawerVisible = ref(false);
const drawerProps = ref<DrawerProps>({
  title: "",
  row: {},
  row1: {},
  readonly: true
});
// 接收父组件传过来的参数
const acceptParams = (params: DrawerProps) => {
  drawerProps.value = params;
  drawerVisible.value = true;

  if (drawerProps.value.btn!.operatorType === OperatorType.ADD) {
    drawerProps.value.row = {
      ...drawerProps.value.row,
      ...initValue
    };
  }

  drawerProps.value.row1 = {};
  drawerProps.value.readonly =
    drawerProps.value.btn!.operatorType !== OperatorType.ADD && drawerProps.value.btn!.operatorType !== OperatorType.EDIT;
};

// 提交数据（新增/编辑/审核）
const handleSubmit = async () => {
  proForm.value?.element!.validate(async valid => {
    if (!valid) return;
    const fireInfo: Mod.FireInfo = {
      modId: config.modId,
      machineId: config.machineId!,
      eventId: drawerProps.value.btn!.code,
      instanceId: drawerProps.value.row.instance_id,
      result: drawerProps.value.row1._result,
      opinion: drawerProps.value.row1._opinion,
      data: drawerProps.value.row
    };
    await fireModData(fireInfo);
    ElMessage.success({ message: `${drawerProps.value.title}成功！` });
    drawerProps.value.getTableList!();
    drawerVisible.value = false;
  });
};

defineExpose({
  acceptParams
});
</script>
